﻿/*

The MIT License

Copyright (c) 2010 Cartesian Analytics, Inc. 

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

*/

using System;
using System.Collections.Generic;
using System.Linq;
using Pipra.Math;

namespace Pipra.Uom
{
    /// <summary>
    /// A concatenated list of value converters that can be executed in sequence.
    /// </summary>
    public class ValueConverterList :
        System.Collections.ObjectModel.ReadOnlyCollection<IValueConverter<double>>,
        IValueConverter<double>
    {
        /// <summary>
        /// Reduces a set of value converters.
        /// </summary>
        /// <param name="converters">The converters to reduce.</param>
        /// <returns>A reduced set of converters.</returns>
        public static IEnumerable<IValueConverter<double>> Reduce(IEnumerable<IValueConverter<double>> converters)
        {
            var results = new List<IValueConverter<double>>();
            converters = Linearize(converters);
            IEnumerator<IValueConverter<double>> enumerator = converters.GetEnumerator();
            if (enumerator.MoveNext())
            {
                bool moveOk;
                do
                {
                    IValueConverter<double> converter;
                    moveOk = Reduce(enumerator, out converter);
                    if (null != converter)
                    {
                        results.Add(converter);
                    }
                } while (moveOk);
            }
            return results;
        }

        private static bool Reduce(IEnumerator<IValueConverter<double>> converters, out IValueConverter<double> converter)
        {
            if (null != converters.Current)
            {
                if (converters.Current is FactorValueConverter)
                {
                    var factorValueConverters = new List<FactorValueConverter>
                        {converters.Current as FactorValueConverter};
                    bool moveOk;
                    while ((moveOk = converters.MoveNext()) && converters.Current is FactorValueConverter)
                    {
                        factorValueConverters.Add(converters.Current as FactorValueConverter);
                    }
                    if (1 == factorValueConverters.Count)
                    {
                        converter = factorValueConverters[0];
                    }
                    else
                    {
                        ConversionFactorEntry entry = ConversionFactorEntry.Reduce(factorValueConverters.Select(fvc => fvc.Entry));
                        converter = FactorValueConverter.CreateConverter(
                            factorValueConverters[0].Type,
                            factorValueConverters[0].From,
                            factorValueConverters[factorValueConverters.Count - 1].To,
                            entry
                        );
                    }
                    return moveOk;
                }
            }
            converter = converters.Current;
            return converters.MoveNext();
        }

        private static IEnumerable<IValueConverter<double>> Linearize(IEnumerable<IValueConverter<double>> converters)
        {
            return converters.SelectMany(c =>
                c is IEnumerable<IValueConverter<double>>
                ? Linearize(c as IEnumerable<IValueConverter<double>>)
                : new[] { c }
            );
        }
        /// <summary>
        /// Constructs a new value converter list from the given converters.
        /// </summary>
        /// <param name="converters">The converters to use.</param>
        /// <remarks>
        /// The converters may be reduced.
        /// </remarks>
        public ValueConverterList(IEnumerable<IValueConverter<double>> converters)
            : base(
                new List<IValueConverter<double>>(Reduce(converters ?? Enumerable.Empty<IValueConverter<double>>()))
                ) { }

        public string Type
        {
            get
            {
                return (
                    Count > 0
                    ? this[0].Type
                    : null
                );
            }
        }

        public IUom From
        {
            get
            {
                return (
                    Count > 0
                    ? this[0].From
                    : null
                );
            }
        }

        public IUom To
        {
            get
            {
                return (
                    Count > 0
                    ? this[Count - 1].To
                    : null
                );
            }
        }

        public int OpCost
        {
            get { return this.Sum(conv => conv.OpCost); }
        }

        public double TransformValue(double value)
        {
            for (int i = 0; i < Count; i++)
            {
                value = this[i].TransformValue(value);
            }
            return value;
        }

        [CLSCompliant(false)]
        public void TransformValue(ref double value)
        {
            for (int i = 0; i < Count; i++)
            {
                this[i].TransformValue(ref value);
            }
        }

        public void TransformValues(double[] values)
        {
            for (int i = 0; i < Count; i++)
            {
                this[i].TransformValues(values);
            }
        }

        public IEnumerable<double> TransformValues(IEnumerable<double> values)
        {
            for (int i = 0; i < Count; i++)
            {
                values = this[i].TransformValues(values);
            }
            return values;
        }

        public bool HasInverse
        {
            get { return this.All(t => t.HasInverse); }
        }

        ITransformation<double> ITransformation<double>.GetInverse()
        {
            return GetInverse();
        }

        ITransformation<double, double> ITransformation<double, double>.GetInverse()
        {
            return GetInverse();
        }

        ITransformation ITransformation.GetInverse()
        {
            return GetInverse();
        }

        IValueConverter IValueConverter.GetInverse()
        {
            return GetInverse();
        }

        public IValueConverter<double> GetInverse()
        {
            return new ValueConverterList(
                this
                .Select(t => t.GetInverse())
                .Reverse()
            );
        }
    }
}
